class ProjectController < ApplicationController
  before_filter :login_required

  
  def index
    @projects = session['user'].projects(true).sort_by {|p| p.updated_on}.reverse
    #@projects = Project.find(:all, :conditions=>"", :joins=>"", :order => :created_on)
  end
  
  def update
    begin
      @project = Project.find(params[:id])
      @project.update_attributes!(params[:project])
      flash[:notice] = 'Project was successfully updated.'
      rescue Exception => e
      flash[:notice] = e.message
    end
    redirect_to :action=>:edit, :id=>@project
  end
  
  # create a new project
  def add
    begin
      name = params[:new][:name]
      if(name=="")
        flash[:notice] = "Empty name"
        redirect_to(:action => "index")
        return
      end
      t = Project.find(:first, :include => [:users], :conditions => "projects.name='#{name}' and users.id='#{session['user'].id}'")
      if(t)
        flash[:notice] = "You already have a project called #{t.name}"
        redirect_to(:action => "index")
        return
      end
      t = Project.new(params[:new])
      t.save!
      t.users << session['user']
      flash[:notice] = "#{t.name} has been created and you have been added as a member"
      redirect_to(:action => "edit", :id => t)
      rescue Exception => e
      flash[:notice] = e
      redirect_to(:action => "index")
    end
    
  end
  
  def edit
    @project = Project.find(params[:id])
    if(not @project.users.member?(session['user']))
      render_text 'No permission to edit this project'
      return
    end
    @users = User.find(:all,:order=>"name").map {|u| [u.name, u.id]}
  end
  
 
  # Ajaxized
  #def delete
  #  if Project.destroy(params[:id]) == 0
  #    render (:text=>"This project did not exist")
  #  else
  #    render (:text=>"document.getElementById('notice').innerHTML= 'project has been deleted';var el=document.getElementById('tr#{params[:id]}');new Effect.Fade(el,{delay:1});")
  #  end
  #end
  
end
